#include <stdio.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
#include<signal.h>
#include<wait.h>

void recyleChild(int arg){
    //回收资源
    while(1){
        int ret = waitpid(-1, NULL, WNOHANG);
        if(ret == -1){
            //所有的子进程都回收完了
            break;
        }
        else if(ret == 0){
            //还有子进程活着
            break;
        }
        else{
            printf("子进程 %d 被回收了！\n",ret);
        }
    }
}

int main(){

    struct sigaction act;
    act.sa_flags = 0;
    sigemptyset(&act.sa_mask);
    act.sa_handler = recyleChild;

    //注册信号捕捉
    sigaction(SIGCHLD, &act, NULL);

    //1、创建socket
    int lfd = socket(PF_INET, SOCK_STREAM, 0);
    if(lfd == -1){
        perror("socket");
        exit(-1);
    }

    //2、绑定
    struct sockaddr_in saddr;
    saddr.sin_family = AF_INET;
    saddr.sin_port = htons(9999);
    saddr.sin_addr.s_addr = INADDR_ANY;
    int ret = bind(lfd,(struct sockaddr *)&saddr, sizeof(saddr));
    if(ret == -1){
        perror("bind");
        exit(-1);
    }

    //3、监听
    ret = listen(lfd, 128);
    if(ret == -1){
        perror("listen");
        exit(-1);
    }

    //4、不断的循环，等待客户端连接
    while(1){
        struct sockaddr_in cliaddr;
        int len = sizeof(cliaddr);
        //接受连接,获得一个通信的文件描述符
        int cfd = accept(lfd, (struct sockaddr*)&cliaddr, &len);
        if(cfd == -1){
            if(errno == EINTR){
                continue;
            }
            perror("accept");
            exit(-1);
        }

        //每连接一个进来，创建一个子进程跟客户端通信
        pid_t pid = fork();
        if(pid == 0){
            //说明是子进程，子进程进行的操作：获取客户端的信息
            char cliIP[16];
            inet_ntop(AF_INET, &cliaddr.sin_addr.s_addr, cliIP, sizeof(cliIP));
            unsigned short cliPort = ntohs(cliaddr.sin_port);
            printf("client ip: %s, client port: %d\n", cliIP, cliPort);
            //接受客户端发来的数据
            char recvBuf[1024] = {0};
            while(1){
                int datalen = read(cfd, &recvBuf, sizeof(recvBuf));
                if(datalen == -1){
                    perror("read");
                    exit(-1);
                }
                else if(datalen > 0){
                    printf("receive client data: %s\n", recvBuf);
                }
                else{
                    printf("client closed...");
                    break;
                }
                //将收到的数据返回给客户端
                write(cfd, recvBuf, strlen(recvBuf));
            }
            close(cfd);
        }
    }

    close(lfd);
    return 0;
}